//获取应用实例
const app = getApp();
// 引入AES.js
var baseJs = require("../../common/base.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUrl: baseJs.imgUrl,
    orderNum: {},
    orderData: [],
    showType: '核销中',
    pageIndex: 1,
    state: '',
    fiveData: [{
        'title': '待兑换',
        'active': true,
        'src0': "../../images/icon/order_2.png",
        'src1': "../../images/icon/order2.png",
        'showType': "核销中"
      },
      {
        'title': '交易完',
        'active': false,
        'src0': "../../images/icon/order_5.png",
        'src1': "../../images/icon/order5.png",
        'showType': "交易结束"
      }
    ],
    // 核销
    hotelFlag: true,
    heXiaoCarNumber: "",
    consumerNumber:"",
    // 
    uid:"",
    userType:"",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      uid: wx.getStorageSync('uid'),
      userType: wx.getStorageSync('userType')
    })
    this.GetExchangeOrderStateNum();
    this.GetOrderList();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    this.data.pageIndex++;
    this.GetExchangeOrderStateNum();
  },

  // 
  showTypeTap: function(e) {
    console.log(e);
    var fiveData = this.data.fiveData;
    var showType = e.currentTarget.dataset.showtype;
    for (var i = 0, len = fiveData.length; i < len; ++i) {
      if (fiveData[i].showType == showType) {
        fiveData[i].active = true;
      } else {
        fiveData[i].active = false
      }
    }
    this.setData({
      fiveData: fiveData,
      showType: showType
    })
    this.data.pageIndex = 1;
    this.data.orderData = [];
    this.GetOrderList();
    console.log(showType);
  },
  // 得到订单状态所有的个数
  GetExchangeOrderStateNum: function() {
    var that = this;
    var uid = this.data.uid;
    var orderNum = this.data.orderNum;
    var fiveData = this.data.fiveData;
    wx.request({
      url: baseJs.api + baseJs.encryUrl("method=GetBusinessOrderStateNum&UID=" + uid + "&Type=2"),
      success: function(res) {
        orderNum = JSON.parse(baseJs.decryUrl(res.data)).ResultData;
        fiveData[0].num = orderNum.waitFinished;
        fiveData[1].num = orderNum.finished;
        that.setData({
          orderNum: orderNum,
          fiveData: fiveData,
        })
        console.log(orderNum);
      }
    })
  },
  //加载订单列表
  GetOrderList: function() {
    var that = this;
    var uid = this.data.uid;
    var showType = this.data.showType;
    var pageIndex = this.data.pageIndex;
    var orderData = this.data.orderData;
    if (pageIndex == 1) {
      wx.showLoading({
        title: '加载中',
      })
    }
    wx.request({
      url: baseJs.api + baseJs.encryUrl("method=GetOrderList&UID=" + uid + "&Type=2&DeliverGoods=1&IsBusinessOrder=0&PageSize=10&PageIndex=" + pageIndex + "&OrderState=" + showType),
      success: function(res) {
        var json = JSON.parse(baseJs.decryUrl(res.data)).ResultData;
        for (var i = 0; i < json.length; i++) {
          orderData.push(json[i])
        }
        that.setData({
          orderData: orderData,
        })
        if (json.length == 10) {
          that.setData({
            state: 'loadMore',
          })
        } else if (json.length == 0 && pageIndex == 1) {
          that.setData({
            state: 'noData',
          })
        } else if (json.length < 10) {
          that.setData({
            state: 'noMore',
          })
        } else if (json.length == 0 && pageIndex > 1) {
          that.setData({
            state: 'noMore',
          })
        }
        wx.hideLoading();
        console.log(orderData);
        console.log(baseJs.api + "method=GetOrderList&UID" + uid + "&Type=1&DeliverGoods=1&IsBusinessOrder=0&PageSize=10&PageIndex=" + pageIndex + "&OrderState=" + showType);
      }
    })
  },

  // 删除
  delOrder: function(e) {
    var that = this;
    var uid = this.data.uid;
    var orderData = this.data.orderData;
    wx.showModal({
      title: '提示',
      content: '确认删除该订单吗？',
      success: function(res) {
        if (res.confirm) {
          // console.log('用户点击确定');
          wx.request({
            url: baseJs.api + baseJs.encryUrl("method=DeleteOrder&UID=" + uid + "&OrderNumber=" + e.currentTarget.dataset.ordernumber + "&IsBusinessOrder=0"),
            success: function(res) {
              if (JSON.parse(baseJs.decryUrl(res.data)).ResultFlag == 1) {
                wx.showToast({
                  title: JSON.parse(baseJs.decryUrl(res.data)).ResultMsg,
                  icon: 'none',
                  duration: 2000
                });
                orderData.splice(e.currentTarget.dataset.index, 1);
                that.setData({
                  orderData: orderData
                })
                that.GetExchangeOrderStateNum();
              } else {

              }
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消');
        }
      }
    })
  },
  // 确认核销
  confirmTap: function(e) {
    console.log(e);
    var that = this;
    // 会员绑定的车牌号
    var heXiaoCarNumber = this.data.heXiaoCarNumber;
    var consumerNumber = this.data.consumerNumber;
    that.setData({
      heXiaoCarNumber: e.currentTarget.dataset.carnumber,
      consumerNumber: e.currentTarget.dataset.consumernumber,
    })
    if (e.currentTarget.dataset.orderarea == 1) {
      wx.showModal({
        title: '提示',
        content: '确认核销订单吗？',
        success: function(res) {
          if (res.confirm) {
            wx.showModal({
              title: '核验信息',
              content: '姓名：' + e.currentTarget.dataset.name + '，身份证号：' + e.currentTarget.dataset.idcard,
              success: function(res) {
                if (res.confirm) {
                  console.log('用户点击确定');
                } else if (res.cancel) {
                  console.log('用户点击取消');
                }
              }
            })
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        }
      })
    } else if (e.currentTarget.dataset.orderarea == 2) {
      wx.showModal({
        title: '提示',
        content: '确认核销订单吗？',
        success: function (res) {
          if (res.confirm) {
            that.chooseImg();
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        }
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '确认核销订单吗？',
        success: function(res) {
          if (res.confirm) {
            // 测试
            // that.chooseImg();
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        }
      })
    }
  },
  // 
  // chooseImg
  chooseImg: function(e) {
    var that = this;
    var base64 = this.data.base64;
    var imgUrl = this.data.imgUrl;
    // 会员绑定的车牌号
    var heXiaoCarNumber = this.data.heXiaoCarNumber;
    // 
    wx.chooseImage({
      // 最多可以选择的图片张数，默认9
      count: 1,
      // 可以指定是原图还是压缩图，默认二者都有
      sizeType: ['original', 'compressed'],
      // 可以指定来源是相册还是相机，默认二者都有
      // sourceType: ['camera'],
      sourceType: ['album', 'camera'],
      success: function(res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths[0];
        wx.request({
          url: tempFilePaths,
          method: 'GET',
          responseType: 'arraybuffer',
          success: function(res) {
            base64 = wx.arrayBufferToBase64(res.data);
            that.setData({
              base64: base64,
            })
            // console.log(base64)
            wx.request({
              url: baseJs.api + baseJs.encryUrl("method=BuluoAreaCarNumberIdentify"),
              header: {
                "Content-Type": "application/x-www-form-urlencoded"
              },
              method: 'post',
              data: baseJs.json2Form({
                CarImg: base64,
              }),
              success: function(res) {
                console.log(res);
                if (res.data.ResultData.ret == 200){
                  if (heXiaoCarNumber == res.data.ResultData.data.number){
                    wx.showModal({
                      title: '提示',
                      content: '绑定车牌号是' + heXiaoCarNumber + '，当前车牌号是' + res.data.ResultData.data.number + '，请确定是否核销？',
                      success: function (res) {
                        if (res.confirm) {

                        } else if (res.cancel) {
                          console.log('用户点击取消');
                        }
                      }
                    })
                  }else{
                    wx.showModal({
                      title: '提示',
                      showCancel:false,
                      confirmText:'暂不核销',
                      content: '绑定车牌号是' + heXiaoCarNumber + '，当前车牌号是' + res.data.ResultData.data.number + '，请核对当前车辆是否为会员身份！',
                      success: function (res) {
                        if (res.confirm) {

                        } else if (res.cancel) {
                          console.log('用户点击取消');
                        }
                      }
                    })
                  }
                }else{
                  wx.showToast({
                    title: "车牌号识别有误, 请重新识别",
                    icon: 'none',
                    duration: 3000
                  });
                }
              }
            })
          }
        })
      }
    })
  },
  // 核销
  FinishedExchangeOrder: function () {
    var that = this;
    var consumerNumber = this.data.consumerNumber;
    console.log(consumerNumber);
    wx.request({
      url: baseJs.api + baseJs.encryUrl("method=FinishedExchangeOrder&ConsumerNumber=" + consumerNumber),
      success: function (res) {
        var json = JSON.parse(baseJs.decryUrl(res.data));
        console.log(json);
      }
    })
  },
})